from . import application, db
from flask import render_template, request, redirect, make_response
from .models import User, Group, Link

# home
@application.route('/')
def index():
    #判断是否已经登录
    uname = request.cookies.get('username')
    if uname:
        # 查询该用户的导航信息
        user = User.query.filter(User.username == uname).first()
        return render_template('index.html', user=user, groups=user.groups)
    else:
        return render_template('login.html')

@application.route('/link/add', methods=['POST'])
def add_link():
    link = Link(gid=request.form['gid'], uid=request.form['uid'], title=request.form['title'], url=request.form['url'], desc=request.form['desc'])
    db.session.add(link)
    db.session.commit()
    return "添加成功！"

@application.route('/group/add', methods=['POST'])
def add_group():
    group = Group(uid=request.form['uid'], title=request.form['title'])
    db.session.add(group)
    db.session.commit()
    return "添加成功！"

# login
@application.route('/login', methods=['POST'])
def login():
    error = None
    uname = request.form['username']
    pwd = request.form['password']
    if (uname and pwd) :
        print("uname={}, pwd={}".format(uname, pwd))
        user = User.query.filter(User.username == uname).first()
        if user:
            if (user.password == pwd):
                resp = make_response(redirect('/'))
                resp.set_cookie('username', user.username)
                return resp
            else:
                return render_template('login.html', error="用户{}的密码不正确。".format(uname))
        else:
            return render_template('login.html', error="用户{}不存在。".format(uname))
    else:
        return render_template('login.html')
